<template>
  <div>
    <el-dialog
      title="发放问卷"
      :visible.sync="isshow"
      width="530px"
      @close="concle"
    >
      <span>{{ title }}</span>
      <div>
        <p class="required">接收人</p>
        <div class="box">
          <div class="item">
            <div class="head">
              <el-checkbox v-model="teachersCheckAll" @change="teacherFull"
                >教师（{{ teacherNum }}）</el-checkbox
              >
            </div>
            <div v-loading="teacherLoading" class="tree studentTree">
              <el-tree
                v-if="!teacherLoading"
                node-key="id"
                :data="teacthers"
                show-checkbox
                ref="teatree"
                :default-checked-keys="checkTeacthers"
                @check="conteaclecheckall"
              >
              </el-tree>
            </div>
          </div>
          <div class="item">
            <div class="head">
              <el-checkbox @change="studentFull" v-model="studentsCheckAll"
                >学生（{{ studentNum }}）</el-checkbox
              >
            </div>
            <div v-loading="studentLoading" class="tree studentTree">
              <el-tree
                v-if="!studentLoading"
                node-key="id"
                :data="studentData"
                show-checkbox
                ref="stutree"
                :default-checked-keys="checkstudents"
                @check="constuclecheckall"
              >
              </el-tree>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="concle" round>取 消</el-button>
        <el-button type="primary" @click="confirmSend" round>发放</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPost_teacher } from "@/api/schoolOrganization/teacher";
import {
  getStudents,
  changeQuestion,
  getacceptUser,
} from "../../../api/questions/index";
export default {
  name: "MixedStateAdminSendQuestion",

  data() {
    return {
      studentData: [],
      isshow: false,
      title: "",
      defaultProps: {
        label: "lable",
        children: "children",
      },
      count: 1,
      teacthers: [],
      students: "",
      checkTeacthers: [],
      checkstudents: [],
      teachersIsIndeterminate: false,
      teachersCheckAll: false,
      studentsCheckAll: false,
      id: undefined,
      acceptId: [],
      studentLoading: true,
      teacherLoading: true,
      teacherNum: 0,
      studentNum: 0,
    };
  },
  methods: {
    // 获取教师列表 teacherId name
    getTeacher() {
      this.teacherLoading = true;
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then(async (response) => {
        //TODO 处理教师
        this.teacthers = await this.handleTeachterData(response.rows);
        this.teacherLoading = false;
      });
    },
    // 获取学生列表
    getstudent() {
      this.studentLoading = true;
      getStudents().then(async (res) => {
        this.studentData = await this.handleStudentData(res.data);
        this.studentLoading = false;
      });
    },
    // 处理学生数据，将数据处理成树状结构
    handleStudentData(data) {
      let that = this;
      var result = data.reduce(function (acc, obj) {
        var branchObj = acc.find(function (el) {
          return el.id === obj.branch_id;
        });

        if (!branchObj) {
          branchObj = {
            id: obj.branch_id,
            label: obj.branch_name,
            children: [],
          };
          acc.push(branchObj);
        }

        var majorObj = branchObj.children.find(function (el) {
          return el.id === obj.major_id;
        });

        if (!majorObj) {
          majorObj = {
            id: obj.major_id,
            label: obj.major_name,
            children: [],
          };
          branchObj.children.push(majorObj);
        }

        var classObj = majorObj.children.find(function (el) {
          return el.id === obj.class_id;
        });

        if (!classObj) {
          classObj = {
            id: obj.class_id,
            label: obj.class_name,
            children: [],
          };
          majorObj.children.push(classObj);
        }
        const disabled = that.acceptId.includes(obj.user_id) || false;
        const studentObj = {
          ...obj,
          id: obj.user_id,
          label: obj.name,
          disabled,
        };
        classObj.children.push(studentObj);

        return acc;
      }, []);
      // 处理学生已发放

      return result;
    },
    // 处理教师数据，处理为树状结构
    handleTeachterData(data) {
      let that = this;
      var result = data.reduce(function (acc, obj) {
        var branchObj = acc.find(function (el) {
          return el.id === obj.branchId;
        });

        if (!branchObj) {
          branchObj = {
            id: obj.branchId,
            label: obj.branchName,
            children: [],
          };
          acc.push(branchObj);
        }
        const disabled = that.acceptId.includes(obj.userId) || false;
        const teacherObj = {
          ...obj,
          id: obj.userId,
          label: obj.name,
          disabled,
        };
        branchObj.children.push(teacherObj);

        return acc;
      }, []);
      return result;
    },
    // 学生全选
    studentFull() {
      let arr = [];
      if (this.studentsCheckAll) {
        this.studentData.forEach((e) => {
          e.children.forEach((o) => {
            o.children.forEach((i) => {
              i.children.forEach((n) => {
                if (!n.disabled) {
                  arr.push(n.user_id);
                }
              });
            });
          });
        });
        this.checkstudents = arr;
      } else {
        this.checkstudents.splice(0, this.checkstudents.length);
        if (this.checkstudents.length == 0) {
          this.$nextTick(() => {
            this.$refs.stutree.setCheckedKeys([]);
          });
        }
      }
      this.studentNum = this.checkstudents.length;
    },
    // 教师全选
    teacherFull() {
      if (this.teachersCheckAll) {
        let arr = [];
        this.teacthers.forEach((e, i) => {
          e.children.forEach((o, index) => {
            if (!o.disabled) {
              arr.push(o.userId);
            }
          });
        });
        this.checkTeacthers = arr;
      } else {
        this.checkTeacthers.splice(0, this.checkTeacthers.length);
        if (this.checkTeacthers.length == 0) {
          this.$nextTick(() => {
            this.$refs.teatree.setCheckedKeys([]);
          });
        }
      }
      this.teacherNum = this.checkTeacthers.length;
    },
    // 学生反选
    constuclecheckall(e, n) {
      let arr = [];
      if (this.studentData != []) {
        this.studentData.forEach((e) => {
          e.children.forEach((o) => {
            o.children.forEach((i) => {
              i.children.forEach((n) => {
                if (!n.disabled) {
                  arr.push(n.user_id);
                }
              });
            });
          });
        });
      }

      let arr1 = [];
      n.checkedNodes.forEach((e) => {
        if (e.user_id) {
          arr1.push(e.user_id);
        }
      });
      this.studentNum = arr1.length;
      if (arr.length == arr1.length) {
        this.studentsCheckAll = true;
      } else {
        this.studentsCheckAll = false;
      }
    },
    // 教师反选
    conteaclecheckall(e, n) {
      let arr = [];
      if (this.teacthers != []) {
        this.teacthers.forEach((e, i) => {
          e.children.forEach((o, index) => {
            if (!o.disabled) {
              arr.push(o.userId);
            }
          });
        });
      }
      let arr1 = [];
      n.checkedNodes.forEach((e) => {
        if (e.userId) {
          arr1.push(e.userId);
        }
      });
      this.teacherNum = arr1.length;
      if (arr.length == arr1.length) {
        this.teachersCheckAll = true;
      } else {
        this.teachersCheckAll = false;
      }
    },
    show(row) {
      this.isshow = true;
      this.title = row.surveyName;
      this.id = row.id;
      this.acceptUser();
    },
    // TODO:获取选中数组
    confirmSend() {
      this.checkstudents = this.$refs.stutree.getCheckedKeys();
      this.checkTeacthers = this.$refs.teatree.getCheckedKeys();
      // 调取发送接口发送数据
      if (this.sendmsg()) {
        this.isshow = false;
      }
    },
    // 发放
    sendmsg() {
      let statu = this.sendisno();
      if (statu) {
        let userId = this.checkstudents.concat(this.checkTeacthers).join(",");
        changeQuestion({
          surveyId: this.id,
          userIds: userId,
          // userIds: 906,
          surveyStatus: 1,
        }).then((res) => {
          this.$emit("sendQuestionSucess");
        });
      } else {
        this.$modal.msgError("请选择发放用户");
      }
      return statu;
    },
    // 校验是否有选择发放用户
    sendisno() {
      let statu = true;
      if (this.checkstudents.concat(this.checkTeacthers).length == 0) {
        statu = false;
      }
      return statu;
    },
    // 获取收到问卷用户
    async acceptUser() {
      let res = await getacceptUser({ surveyId: this.id });
      this.getTeacher();
      this.getstudent();
      this.acceptId = res.data || [];
    },
    concle() {
      this.checkTeacthers = [];
      this.checkstudents = [];
      this.teachersCheckAll = false;
      this.studentsCheckAll = false;
      (this.teacherNum = 0), (this.studentNum = 0), (this.isshow = false);
    },
  },
};
</script>

<style lang="scss" scoped>
.required::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.required {
  margin-top: 20px;
}
.box {
  display: flex;
}
.item {
  margin-right: 40px;
}
.tree {
  width: 200px;
  box-shadow: 0px 0px 10px 2px #ddd;
  display: flex;
  flex-direction: column;
  padding: 10px;
  margin-top: 10px;
}
.studentTree {
  height: 400px;
  overflow: auto;
}
.head {
  padding-left: 10px;
  margin-top: 10px;
}
</style>
